<!-- eslint-disable array-callback-return -->
<template>
  <div>
    <van-nav-bar title="城市列表" class="title">
      <template #left>
        <van-icon name="arrow-left" color="#ffffff" @click="$router.go(-1)" />
      </template>
    </van-nav-bar>
    <!-- indexBar -->
    <van-index-bar :index-list="indexlist">
      <template v-for="(item, index) in indexlist">
        <van-index-anchor :key="index" :index="item">
          {{ item }}
          <van-cell
            v-for="obj in anchorlist[item]"
            :title="obj.label"
            :key="obj.short"
          />
        </van-index-anchor>
      </template>
    </van-index-bar>
  </div>
</template>

<script>
import { getHotCityList, getCityList } from '@/api/city'
export default {
  name: 'city-list',
  data() {
    return {
      indexlist: [],
      anchorlist: []
    }
  },
  async created() {
    const obj = {}
    const currentCtiy = JSON.parse(window.localStorage.getItem('current')) || {
      label: '北京',
      pinyin: 'beijing',
      short: 'bj',
      value: 'AREA|88cff55c-aaa4-e2e0'
    }
    obj['#'] = [currentCtiy]
    const { body } = await getHotCityList()
    obj['热'] = body
    const { body: citylist } = await getCityList()
    citylist.forEach((item) => {
      const key = item.short[0].toUpperCase()
      if (obj[key]) {
        obj[key].push(item)
      } else {
        obj[key] = [item]
      }
    })
    // 索引
    const arr = Object.keys(obj)
    arr.sort()
    const item1 = arr.pop()
    const item2 = arr.shift()
    arr.unshift(item2, item1)
    this.indexlist = arr
    this.anchorlist = obj
  },
  methods: {}
}
</script>

<style lang="less" scoped>
::v-deep .title {
  background-color: #21b97a;
}
</style>
